package database.didactic;

import database.ConnectionFactory;
import database.util.Queries;
import model.didactic.ActivityType;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: kosta
 * Date: 1/1/13
 * Time: 7:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class ActivityTypeDao {

    public static ArrayList<ActivityType> getActivityTypes(){
        ArrayList<ActivityType> result = new ArrayList<ActivityType>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = ConnectionFactory.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery(Queries.ACTIVITY_TYPES_SELECT_QUERY);
            result = toActivityTypes(resultSet);
        } catch (SQLException e) {
            System.err.println("ActivityTypeDao.getActivityTypes Error db");
            e.printStackTrace();
        } finally {
            try{
                if (resultSet!=null) resultSet.close();
                if (statement!=null) statement.close();
                if (connection!=null) connection.close();
            } catch (SQLException e) {
                System.err.println("ActivityTypeDao.getActivityTypes finally block error");
            }
        }
        return result;
    }





    private static ArrayList<ActivityType> toActivityTypes(ResultSet rs){
        ArrayList<ActivityType> result = new ArrayList<ActivityType>();
        try {
            while (rs.next()) {
                ActivityType activityType=toActivityType(rs);
                result.add(activityType);
            }
        } catch (SQLException e) {
            System.err.println("toActivityTypes ResultSetError");
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("toActivityTypes unknown ResultSetError");
            e.printStackTrace();
        }
        return result;
    }

    private static ActivityType toActivityType(ResultSet rs) throws SQLException {
        if (rs == null || rs.isClosed()){
            throw new SQLException("ResultSet Closed !!!");
        }
        ActivityType activityType;
        activityType=new ActivityType();
        activityType.setId(rs.getInt(1));
        activityType.setTypeName(rs.getString(2));
        activityType.setDescription(rs.getString(3));

        return activityType;
    }

}
